﻿package {
	import Mode.RoleType;
	
	import View.Background;
	import View.Role;
	
	import laya.display.Animation;
	import laya.display.Stage;
	import laya.display.Text;
	import laya.events.Event;
	import laya.media.SoundManager;
	import laya.net.Loader;
	import laya.utils.Browser;
	import laya.utils.Handler;
	import laya.utils.Pool;
	import laya.utils.Stat;

	public class PlaneWar 
	{
		
		public function PlaneWar() 
		{
			//初始化引擎
			Laya.init(480,STAGE_HEIGHT);
			
			Laya.stage.alignV = Stage.ALIGN_MIDDLE;
			Laya.stage.alignH = Stage.ALIGN_CENTER;
			Laya.stage.screenMode = Stage.SCREEN_VERTICAL;
			
			Laya.stage.scaleMode = Stage.SCALE_SHOWALL;
			Laya.stage.bgColor = "#232628";
			Stat.show(Browser.clientWidth - 120, 0);
			
			bg = new Background();
			Laya.stage.addChild(bg);
			
			Laya.loader.load("res/atlas/war.json", Handler.create(this, this.onLoaded), null, Loader.ATLAS);
		}
		
		private function onMouseMove():void
		{
			hero.pos(Laya.stage.mouseX,Laya.stage.mouseY);		
		}
		
		private function onLoaded():void
		{
			//缓存hero_fly动画
			Animation.createFrames(["war/hero_fly1.png", "war/hero_fly2.png"], "hero_fly");
			//缓存hero_down动画
			Animation.createFrames(["war/hero_down1.png", "war/hero_down2.png", "war/hero_down3.png", "war/hero_down4.png"], "hero_down");
			
			//缓存enemy1_fly动画
			Animation.createFrames(["war/enemy1_fly1.png"], "enemy1_fly");
			//缓存enemy1_down动画
			Animation.createFrames(["war/enemy1_down1.png", "war/enemy1_down2.png", "war/enemy1_down3.png", "war/enemy1_down4.png"], "enemy1_down");
			
			//缓存enemy2_fly动画
			Animation.createFrames(["war/enemy2_fly1.png"], "enemy2_fly");
			//缓存enemy2_down动画
			Animation.createFrames(["war/enemy2_down1.png", "war/enemy2_down2.png", "war/enemy2_down3.png", "war/enemy2_down4.png"], "enemy2_down");
			//缓存enemy2_hit动画
			Animation.createFrames(["war/enemy2_hit.png"], "enemy2_hit");
			
			//缓存enemy3_fly动画
			Animation.createFrames(["war/enemy3_fly1.png", "war/enemy3_fly2.png"], "enemy3_fly");
			//缓存enemy3_down动画
			Animation.createFrames(["war/enemy3_down1.png", "war/enemy3_down2.png", "war/enemy3_down3.png", "war/enemy3_down4.png", "war/enemy3_down5.png", "war/enemy3_down6.png"], "enemy3_down");
			//缓存enemy3_hit动画
			Animation.createFrames(["war/enemy3_hit.png"], "enemy3_hit");
			//缓存子弹动画
			Animation.createFrames(["war/bullet1.png"], "bullet1_fly");
			Animation.createFrames(["war/bullet2.png"], "bullet2_fly");
			//缓存UFO1
			Animation.createFrames(["war/ufo1.png"], "ufo1_fly");
			//缓存UFO2
			Animation.createFrames(["war/ufo2.png"], "ufo2_fly");
			
			//创建一个主角（主战斗机）
			hero = new Role();
			hero.init("hero", 0, 1, 0, 30);
			hero.shootType = 1;
			hero.shootTime = Browser.now() + 2000;
			//把主角添加到舞台上
			hero.pos(240, 700);
			Laya.stage.addChild(hero);	
			
			initLabels();
			
			Laya.stage.on(Event.MOUSE_MOVE, this, onMouseMove);	
			
			Laya.timer.loop(1, this, onLoop);
		}
		
		/**初始化积分，关卡等显示*/
		private function initLabels():void
		{
			lbScore = new Text();
			lbScore.text = "积分：0";
			lbScore.pos(1,1);
			Laya.stage.addChild(lbScore);
			
			lbLevel = new Text();
			lbLevel.text = "关卡：0";
			lbLevel.pos(1,21);
			Laya.stage.addChild(lbLevel);
			
			lbHP = new Text();
			lbHP.text = "血量：1";
			lbHP.pos(1,41);
			Laya.stage.addChild(lbHP);
		}
		
		private function onLoop():void
		{
			for (var i: Number = Laya.stage.numChildren - 1; i > 0; i--)
			{
				var role: Role = Laya.stage.getChildAt(i) as Role;
				if(role && role.speed)
				{
					role.y += role.speed;
					if (role.y > STAGE_HEIGHT || !role.visible || (role.type == "bullet1" && role.y < -20)) 
					{
						role.removeSelf();
						role.dispose();
						Pool.recover("role", role);
					}
				}
			}
			
			var time: Number = Browser.now();
			//如果当前时间大于下次射击时间
			if (time > hero.shootTime) 
			{
				//更新下次射击时间
				hero.shootTime = time + hero.shootInterval;
				//根据不同子弹类型，设置不同的数量及位置
				var pos: Array = this.bulletPos[role.shootType - 1];
				
				for (var k:int = 0; k < pos.length; k++) 
				{
					var bullet:Role = Pool.getItemByClass("role", Role);
					bullet.init("bullet1", hero.camp, 1, -4 - role.shootType - Math.floor(this.level / 15), 1);
					bullet.pos(hero.x + pos[k], hero.y - hero.hitRadius - 10);
					Laya.stage.addChild(bullet);
				}
				
				//增加子弹发射声音
				SoundManager.playSound("res/sound/bullet.mp3");
				
			}
			//检测碰撞，原理：获取角色对象，一一对比之间的位置，判断是否击中
			var n: Number = Laya.stage.numChildren;
			for (i = Laya.stage.numChildren - 1; i > 0; i--) 
			{
				//获取角色对象1
				var role1: Role = Laya.stage.getChildAt(i) as Role;
				//如果角色已经死亡，则忽略
				if (role1 && role1.hp < 1 || !role1.visible) continue;
				for (var j: Number = i - 1; j > 0; j--) 
				{
					//获取角色对象2
					var role2: Role = Laya.stage.getChildAt(j) as Role;
					//如果角色未死亡，并且阵营不同，才进行碰撞
					if (role2 && role2.hp > 0 && role1.camp != role2.camp)
					{
						//计算碰撞区域
						var hitRadius: Number = role1.hitRadius + role2.hitRadius;
						//根据距离判断是否碰撞
						if (Math.abs(role1.x - role2.x) < hitRadius && Math.abs(role1.y - role2.y) < hitRadius) 
						{
							//碰撞后掉血
							this.lostHp(role1, 1);
							this.lostHp(role2, 1);
							this.score++;
							lbScore.text = "积分："+score;
							//积分大于升级积分，则升级
							if (this.score > this.levelUpScore) 
							{
								//升级关卡
								this.level++;
								lbLevel.text = "关卡："+level;
								//提高下一级的升级难道
								this.levelUpScore += this.level * 5;
							}
						}
					}
				}
			}
			
			//如果主角死亡，则停止游戏循环
			if (this.hero.hp < 1) 
			{
				trace("Game Over!");
				SoundManager.playSound("res/sound/game_over.mp3");
				Laya.timer.clear(this, this.onLoop);
			}
			
			//关卡越高，创建敌机间隔越短
			var cutTime: Number = this.level < 30 ? this.level * 2 : 60;
			//关卡越高，敌机飞行速度越高
			var speedUp: Number = Math.floor(this.level / 6);
			//关卡越高，敌机血量越高
			var hpUp: Number = Math.floor(this.level / 8);
			//关卡越高，敌机数量越多
			var numUp: Number = Math.floor(this.level / 10);
			//生成小飞机
			if (Laya.timer.currFrame % (80 - cutTime) == 0) 
			{
				this.createEnemy(1, 2 + numUp, 3 + speedUp, 1);
			}
			//生成中型飞机
			if (Laya.timer.currFrame % (150 - cutTime * 2) == 0) 
			{
				this.createEnemy(2, 1 + numUp, 2 + speedUp, 2 + hpUp * 2);
			}
			//生成boss
			if (Laya.timer.currFrame % (900 - cutTime * 4) == 0) 
			{
				this.createEnemy(3, 1, 1 + speedUp, 5 + hpUp * 6);
				SoundManager.playSound("res/sound/enemy3_out.mp3");
			}
		}
		
		private function setHP():void
		{
			lbHP.text = "血量："+ hero.hp;
		}
		
		private function lostHp(role: Role, lostHp: Number): void 
		{
			//减血
			role.hp -= lostHp;
			if(role.type == RoleType.UFO1)//增加弹药
			{
				role.visible = false;
				this.bulletLevel++;
				//子弹每升2级，子弹数量增加1，最大数量限制在4个
				this.hero.shootType = Math.min(Math.floor(this.bulletLevel / 2) + 1, 4);
				//子弹级别越高，发射频率越快
				this.hero.shootInterval = 500 - 20 * (this.bulletLevel > 20 ? 20 : this.bulletLevel);
				
				SoundManager.playSound("res/sound/achievement.mp3");
			}
			else if(role.type == RoleType.UFO2)//增加血量
			{
				role.visible = false;
				this.hero.hp++;
				setHP();
				if (this.hero.hp > 10) this.hero.hp = 10;
				
				SoundManager.playSound("res/sound/achievement.mp3");
			}
			else if(role.type == RoleType.HERO)
			{
				if (role.hp <= 0) 
				{
					role.playAction("down");
				} 
				setHP();
			}
			else
			{
				if (role.hp > 0) 
				{
					//如果未死亡，则播放受击动画
					role.playAction("hit");
				} 
				else 
				{
					//如果死亡，则播放爆炸动画
					if (role.isBullet) 
					{
						//如果是子弹，则直接隐藏，下次回收
						role.visible = false;
					} 
					else 
					{
						role.playAction("down");
						SoundManager.playSound("res/sound/"+role.type+"_down.mp3");
						
						if(role.type == RoleType.Enemy+3)//是大型飞机 则掉落一个物品
						{
							var ufo:Role = new Role();
							var type:int = Math.random() < 0.7 ? 1 : 2;
							ufo.init("ufo" + type, role.camp, 1, 1, 15);
							ufo.pos(role.x, role.y);
							Laya.stage.addChild(ufo);
						}
					}
				}
			}
		}
		
		private function createEnemy(type: Number, num: Number, speed: Number, hp: Number):void
		{
			for (var i: Number = 0; i < num; i++)
			{
				//创建敌人
				var enemy: Role = Pool.getItemByClass("role", Role);
				enemy.init(RoleType.Enemy+type, 1, hp, speed, radius[type-1]);
				//随机位置
				enemy.pos(Math.random() * 400 + 40, Math.random() * 200);
				//添加到舞台上
				Laya.stage.addChild(enemy);
			}
		}
		
		private const STAGE_HEIGHT:int = 852;
		
		private var bg:Background;
		/**主角飞机*/
		private var hero: Role;
		//子弹发射偏移位置表
		private var bulletPos: Array = [[0], [-15, 15], [-30, 0, 30], [-45, -15, 15, 45]];
		//敌机被击半径表
		private var radius: Array = [13, 33, 80];
		//关卡等级
		private var level: int = 0;
		//积分成绩
		private var score: int = 0;
		//升级等级所需的成绩数量
		private var levelUpScore: Number = 10;
		/**子弹级别*/
		private var bulletLevel: Number = 0;
		private var lbScore:Text;
		private var lbLevel:Text;
		private var lbHP:Text;
	}
}